<template>
  <div class="service-container">
    <el-card class="filter-card table-card">
      <template #header>
        <div class="table-header">
          <h3>租赁申请管理</h3>
          <div class="search-toggle-area">
            <el-button class="search-toggle-button" @click="toggleSearchBar">
              <el-icon><Search /></el-icon>
            </el-button>
            <el-form :inline="true" :model="queryParams" class="search-form" :class="{'is-hidden': !showSearchBar}">
              <el-form-item label="申请类型">
                <el-select v-model="queryParams.application_type" placeholder="请选择" clearable style="width: 160px">
                  <el-option label="房源租赁" value="房源租赁" />
                  <el-option label="车位租赁" value="车位租赁" />
                </el-select>
              </el-form-item>
              <el-form-item label="审批状态">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 160px">
                  <el-option label="待审核" value="待审核" />
                  <el-option label="审核中" value="审核中" />
                  <el-option label="审核通过" value="审核通过" />
                  <el-option label="审核驳回" value="审核驳回" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>

      <div class="search-bar" v-if="false">
        <el-form :inline="true" :model="queryParams">
            <el-form-item label="申请类型">
                <el-select v-model="queryParams.application_type" placeholder="请选择" clearable style="width: 150px">
                    <el-option label="房源租赁" value="房源租赁" />
                    <el-option label="车位租赁" value="车位租赁" />
                </el-select>
            </el-form-item>
            <el-form-item label="审批状态">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 150px">
                    <el-option label="待审核" value="待审核" />
                    <el-option label="审核中" value="审核中" />
                    <el-option label="审核通过" value="审核通过" />
                    <el-option label="审核驳回" value="审核驳回" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
                <el-button size="small" @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
      </div>

      <el-table 
        :data="applicationList" 
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column prop="application_type" label="申请类型" width="120" align="center" header-align="center" />
        <el-table-column prop="applicant" label="申请人" width="120" align="center" header-align="center" />
        <el-table-column prop="subject" label="租赁标的物" show-overflow-tooltip align="center" header-align="center" />
        <el-table-column prop="application_time" label="申请时间" width="180" align="center" header-align="center" />
        <el-table-column prop="status" label="状态" width="140" align="center" header-align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right" align="center" header-align="center">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="applicationList.length === 0 && !loading" description="暂无租赁申请数据" class="empty-data-placeholder"></el-empty>

      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="total"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="申请详情" width="60%">
        <div v-if="selectedApplication">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="申请ID">{{ selectedApplication.id }}</el-descriptions-item>
                <el-descriptions-item label="申请类型">{{ selectedApplication.application_type }}</el-descriptions-item>
                <el-descriptions-item label="申请人">{{ selectedApplication.applicant }}</el-descriptions-item>
                <el-descriptions-item label="关联公司" v-if="selectedApplication.application_type === '房源租赁'">{{ selectedApplication.company }}</el-descriptions-item>
                <el-descriptions-item label="申请时间" :span="selectedApplication.application_type === '车位租赁' ? 2 : 1">{{ selectedApplication.application_time }}</el-descriptions-item>
                
                <el-descriptions-item label="租赁标的" :span="2">
                    {{ selectedApplication.unit_info.building }} {{ selectedApplication.unit_info.floor }} {{ selectedApplication.unit_info.number }}
                </el-descriptions-item>

                <template v-if="selectedApplication.application_type === '车位租赁' && selectedApplication.vehicle_info">
                    <el-descriptions-item label="关联车辆">{{ selectedApplication.vehicle_info.plate_number }}</el-descriptions-item>
                    <el-descriptions-item label="车辆品牌">{{ selectedApplication.vehicle_info.brand }} {{ selectedApplication.vehicle_info.model }}</el-descriptions-item>
                </template>

                <el-descriptions-item label="期望开始日期">{{ selectedApplication.expected_start_date }}</el-descriptions-item>
                <el-descriptions-item label="期望租期">{{ selectedApplication.expected_duration }}</el-descriptions-item>
                <el-descriptions-item label="审批状态">{{ selectedApplication.status }}</el-descriptions-item>
                <el-descriptions-item label="审批意见">{{ selectedApplication.approval_opinion || '暂无' }}</el-descriptions-item>
            </el-descriptions>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="viewDialogVisible = false">关闭</el-button>
                <el-button 
                  v-if="selectedApplication && selectedApplication.status === '审核中'"
                  type="success" 
                  @click="handleCompleteApproval"
                >
                  完成审批
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog v-model="approveDialogVisible" title="租赁审批" width="40%">
        <el-form :model="approvalForm">
            <el-form-item label="审批操作">
                <el-radio-group v-model="approvalForm.status">
                    <el-radio label="审核通过">通过</el-radio>
                    <el-radio label="审核驳回">驳回</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="审批意见">
                <el-input
                    v-model="approvalForm.approval_opinion"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入审批意见"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="approveDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmApproval">确认</el-button>
            </span>
        </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getLeasingApplicationList, getLeasingApplicationDetail, approveLeasingApplication } from '@/api/services';
import { createContract, generateContractAttachment } from '@/api/finance';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

const applicationList = ref([]);
const loading = ref(false);
const total = ref(0);
const showSearchBar = ref(false);
const queryParams = reactive({
  current: 1,
  size: 10,
  application_type: '',
  status: '',
});

const viewDialogVisible = ref(false);
const selectedApplication = ref(null);
const approveDialogVisible = ref(false);
const currentApplicationId = ref(null);
const approvalForm = reactive({
    status: '审核通过',
    approval_opinion: ''
});

const fetchList = async () => {
  loading.value = true;
  try {
    const response = await getLeasingApplicationList(queryParams);
    if (response.data && response.data.code === 200) {
      applicationList.value = response.data.data.list;
      total.value = response.data.data.total;
    } else {
      applicationList.value = [];
      total.value = 0;
      ElMessage.error(response.data.message || '获取列表失败');
    }
  } catch (error) {
    console.error('Failed to fetch leasing application list:', error);
    ElMessage.error('获取列表失败');
  } finally {
    loading.value = false;
  }
};

const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
};

const handleSearch = () => {
    queryParams.current = 1; // Reset to first page on search
    fetchList();
};

const handleReset = () => {
    queryParams.current = 1;
    queryParams.application_type = '';
    queryParams.status = '';
    fetchList();
};

const handleView = async (row) => {
  try {
    const response = await getLeasingApplicationDetail(row.id);
    if (response.data && response.data.code === 200) {
      selectedApplication.value = response.data.data;
      viewDialogVisible.value = true;
      if (row.status === '待审核') {
        fetchList();
      }
    } else {
      ElMessage.error(response.data.message || '获取详情失败');
    }
  } catch (error) {
    console.error('Failed to fetch leasing details:', error);
    ElMessage.error('获取详情失败');
  }
};

const handleCompleteApproval = () => {
    if (!selectedApplication.value) return;
    currentApplicationId.value = selectedApplication.value.id;
    approvalForm.status = '审核通过';
    approvalForm.approval_opinion = '';
    
    viewDialogVisible.value = false; 
    approveDialogVisible.value = true;
};

const confirmApproval = async () => {
    if (!approvalForm.status) {
        ElMessage.warning('请选择审批操作');
        return;
    }
    if (approvalForm.status === '审核驳回' && !approvalForm.approval_opinion) {
        ElMessage.warning('驳回时必须填写审批意见');
        return;
    }

    try {
        const response = await approveLeasingApplication(currentApplicationId.value, approvalForm);
        if (response.data && response.data.code === 200) {
            ElMessage.success('审批成功');
            approveDialogVisible.value = false;
            
            // 如果审批通过，创建合同
            if (approvalForm.status === '审核通过') {
                try {
                    // 提取纯数字ID，移除可能的前缀
                    const numericId = parseInt(currentApplicationId.value.toString().replace(/\D+/g, ''));
                    
                    const contractResponse = await createContract({
                        application_id: numericId, // 使用纯数字ID
                        application_type: selectedApplication.value.application_type
                    });
                    
                    if (contractResponse.data && contractResponse.data.code === 200) {
                        const contractId = contractResponse.data.data.contract_id;
                        const contractNumber = contractResponse.data.data.contract_number;
                        
                        ElMessage.success(`已自动生成合同: ${contractNumber}`);
                    } else {
                        ElMessage.warning(`审批已通过，但合同创建失败: ${contractResponse.data.message}`);
                    }
                } catch (contractError) {
                    console.error('Failed to create contract:', contractError);
                    ElMessage.warning('审批已通过，但合同创建失败，请手动创建合同');
                }
            }
            
            fetchList();
        } else {
            ElMessage.error(response.data.message || '审批失败');
        }
    } catch (error) {
        console.error('Failed to approve application:', error);
        ElMessage.error('审批失败');
    }
};

const handleCurrentChange = (page) => {
  queryParams.current = page;
  fetchList();
};

const getStatusType = (status) => {
  switch (status) {
    case '待审核': return 'info';
    case '审核中': return 'warning';
    case '审核通过': return 'success';
    case '审核驳回': return 'danger';
    default: return 'info';
  }
}

onMounted(() => {
  fetchList();
});
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.filter-card {
  margin-bottom: 10px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}
</style> 